import { getMaterialCaseList } from '../../api/index'

Page({
  data: {
    materialId: '',
    pageSize: 15,
    currentPage: 1,
    list: []
  },
  change ({ detail }) {
    let index = this.data.list.findIndex(row => row.materialCaseId === detail.materialCaseId)
    if (index > -1) {
      let changeKey = `list[${index}]`
      this.setData({
        [changeKey]: detail
      })
    }
  },
  onReachBottom () {
    this.loadMore()
  },
  async getList () {
    try {
      const { ResultSet } = await getMaterialCaseList({ materialId: this.data.materialId, currentPage: 1, pageLines: this.data.pageSize })
      this.loading = false
      this.alloaded = false
      if (ResultSet.userData.caseList.length) this.data.currentPage = 2
      this.data.isEmpty = ResultSet.userData.caseList.length && ResultSet.userData.caseList.length < this.data.pageSize
      this.setData({
        list: ResultSet.userData.caseList,
        currentPage: this.data.currentPage,
        isEmpty: this.data.isEmpty
      })
      this.loading = false
    } catch (err) {
      this.loading = false
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async loadMore () {
    try {
      if (this.loading || this.alloaded) return
      this.loading = true
      const { ResultSet } = await getMaterialCaseList({ materialId: this.data.materialId, currentPage: this.data.currentPage, pageLines: this.data.pageSize })
      this.alloaded = !ResultSet.userData.caseList.length
      this.data.isEmpty = !ResultSet.userData.caseList.length
      this.setData({ isEmpty: this.data.isEmpty })
      if (ResultSet.userData.caseList.length) {
        this.data.currentPage = this.data.currentPage + 1
        this.data.list.push(...ResultSet.userData.caseList)
        this.setData({
          list: this.data.list,
          currentPage: this.data.currentPage
        })
      }
      this.loading = false
    } catch (err) {
      console.log(err)
      this.loading = false
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  onLoad ({ id }) {
    this.setData({ materialId: id })
    this.getList()
  }
})